package com.qf.servlet;

import com.qf.Utils.DaoUtils;
import com.qf.entity.Admin;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.util.List;
import java.util.UUID;

@WebServlet(urlPatterns = "/register")
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory diskFileItemFactory = new DiskFileItemFactory();
        ServletFileUpload   servletFileUpload = new ServletFileUpload(diskFileItemFactory);
        servletFileUpload.setHeaderEncoding("utf-8");

        //获取表单数据集合
        List<FileItem> items = null;
        try {
            items = servletFileUpload.parseRequest(req);
        }catch (FileUploadException e){
            e.printStackTrace();
        }

        //注册用户信息
        Admin admin = new Admin();

        //反射
        Class cls = admin.getClass();

        //循环处理list表单集合
        if (items != null) {
            for (FileItem item : items) {
                //判定是普通项目
                if (item.isFormField()){
                    System.out.println("表单项"+item.getFieldName()+"="+item.getString("utf-8"));
                    if ("".equals(item.getString("utf-8")) || item.getString("utf-8").contains(" ")) {
                        System.out.println("注册失败");
                        resp.sendRedirect("register.jsp?status=2");
                        return;
                    }
                    if ("power".equals(item.getFieldName())) {
                        admin.setPowers(item.getString());
                        continue;
                    }

                    try {
                        Field field = cls.getDeclaredField(item.getFieldName());
                        field.setAccessible(true);
                        field.set(admin,item.getString("utf-8"));

                    }catch (Exception e){}

                    continue;
                }

                System.out.println("上传的文件名称：" + item.getName());
                System.out.println("上传的文件长度"+ item.getSize());
//                跳过添加用户头像
                if (item.getSize() == 0) {
                    admin.setHeader(null);
                    System.out.println("跳过添加用户头像");
                    continue;
                }
                //设置存入的名字
                String filename = UUID.randomUUID().toString();

                //  判定文件夹是否存在,不存在则创建一个文件夹
                File file = new File(DaoUtils.file );
                System.out.println(file.exists());
                if (!file.exists()) {
                    System.out.println("目录创建完成");
                    file.mkdirs();
                }

                try(  //输入流
                      InputStream in = item.getInputStream();
                      OutputStream out = new FileOutputStream(DaoUtils.file + filename);

                ) {

                    //使用工具类 实现文件的拷贝
                    IOUtils.copy(in, out);
                    //将上传的头像名称，关联到用户信息对象中
                    admin.setHeader(filename);
                }catch (Exception e){
                    System.out.println("失败的上传");
                }
            }
        }
        //保存用户信息
        DaoUtils.addAdmins(admin);
        System.out.println(admin);
        //重定向到登录页面
        resp.sendRedirect("login.jsp");



    }
}
